package arithmetic;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

// 请用2个（或者n个）线程竞争去取出list中的string打印
// 每个list中的string只能被1个而不是多个线程打印
// 每个线程都是从索引0开始到list中取string， 如果要取的索引被别的索引获取了就不能获取
public class ShowMeBug {

    static List<String> list = new ArrayList<>();
    private  static int[]  intArray= new int[]{1, 2, 3, 4, 5,6,7,8,9,10};

    private static AtomicIntegerArray ai = new AtomicIntegerArray(intArray);

    static {
        for (int i = 0; i < 10; ++i) {
            list.add(i + "");
           // ai.set(i,1);
        }
    }

    public static void main(String[] args) {


        new Thread(() -> {
            for (int i = 0; i < list.size(); i++) {
                printList(i);
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < list.size(); i++) {
                printList(i);
            }
        }, "BB").start();

    }


    public static  void printList(int index) {
        if (ai.compareAndSet(index,index+1,0)) {
            System.out.println(Thread.currentThread().getName()+": "+ list.get(index));
        }
    }


}
